//
//  GFResultViewController.m
//  GoodFood
//
//  Created by dllo on 15/11/4.
//  Copyright © 2015年 荣伟峰. All rights reserved.
//

#import "GFResultViewController.h"


@interface GFResultViewController ()<UITableViewDataSource, UITableViewDelegate , BMKLocationServiceDelegate>
@property (nonatomic, strong) BMKLocationService *locationService;
@property (nonatomic, assign) double latitude;//纬度
@property (nonatomic, assign) double longitude;//经度
@property (nonatomic, copy) NSString *keyWord;
@property (nonatomic, copy) NSString *regionId;
@property (nonatomic, copy) NSString *cateName;
@property (nonatomic, assign) NSInteger cityId;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, copy) NSString *regionName;
@property (nonatomic, strong) NSMutableArray *arrayForLastSearchResult;
@property (nonatomic, strong) UITableView *tableViewForResult;
@property (nonatomic, copy) NSString *sessionId;
@end

@implementation GFResultViewController
#pragma mark - 初始化
- (instancetype)initWithKey:(NSString *)keyWord withRegionId:(NSString *)regionId withCate:(NSString *)cateName withCityId:(NSInteger)cityId withRegionName:(NSString *)regionName {
    self = [super init];
    if (self) {
        self.page = 1;
        self.keyWord = keyWord;
        self.regionId = regionId;
        self.cateName = cateName;
        self.cityId = cityId;
        self.regionName = regionName;
        self.app = [[UIApplication sharedApplication] delegate];
        self.sessionId = self.app.session_id;
    }
    return self;
}
#pragma mark - 地图管理
- (void)managerMap {
    
    self.locationService = [[BMKLocationService alloc] init];
    [self.locationService startUserLocationService];
}
#pragma mark - 视图加载
- (void)viewDidLoad {
    [super viewDidLoad];
    [self viewForNavi];
    [self createTableView];
    [self managerMap];
    [self.view bringSubviewToFront:self.waitView];
}
#pragma mark - 导航
- (void)viewForNavi {
    UIView *view = (UIView *)[self.navigationController.view viewWithTag:10001];
    view.backgroundColor = [UIColor redColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth / 2, ScreenHeight / 3, ScreenWidth / 3, ScreenHeight / 4)];
    if (![self.keyWord isEqualToString:@""]) {
        label.text = self.keyWord;
    } else {
        if (![self.cateName isEqualToString:@""]) {
            label.text = self.cateName;
        } else {
            label.text = self.regionName;
        }
    }
    
    
    label.textColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.7];
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = label;
    self.view.backgroundColor = [UIColor lightGrayColor];
    
}
#pragma mark - 定位代理方法
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    
    self.latitude = userLocation.location.coordinate.latitude;
    self.longitude = userLocation.location.coordinate.longitude;
    NSLog(@"ca%f,%f",self.latitude,self.longitude);
    if (self.latitude != 0 && self.longitude != 0) {
        [self.locationService stopUserLocationService];
        

    }
   
}
#pragma mark - 定位结束
- (void)didStopLocatingUser {
    [self handleDataTheLastSearchResult];
    self.locationService.delegate = nil;
}
#pragma mark - 解析最终搜索结果数据
- (void)handleDataTheLastSearchResult {
    if (1 == self.page) {
        self.arrayForLastSearchResult = [NSMutableArray array];
    }
    
    NSString *url = [NSString stringWithFormat:@"http://api.meishixing.com/search/nearby/queryplace/keyword=%@&city_id=%ld&page=%ld&lat=%f&lng=%f&food_category_name=%@&region_id=%@",self.keyWord, self.cityId, self.page,self.latitude,self.longitude, self.cateName, self.regionId];
    NSLog(@"%@",url);
    [AFNetHandle GETWithURL:url body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        NSDictionary *dictionary = [NSDictionary dictionaryWithDictionary:result];
        NSArray *arr = [dictionary objectForKey:@"result"];
        for (NSDictionary *dic in arr) {
            GFNearResturtantModel *model = [GFNearResturtantModel modWithDic:dic];
            [self.arrayForLastSearchResult addObject:model];
        }
        if (arr.count != 0) {
            if (self.arrayForLastSearchResult.count < 10) {
                self.tableViewForResult.footer.hidden = YES;
            } else {
                self.tableViewForResult.footer.hidden = NO;
            }
        } else {
            self.tableViewForResult.footer.hidden = YES;
        }
        if (self.arrayForLastSearchResult.count != 0) {
            [self.tableViewForResult reloadData];
        }
        [self.waitView removeFromSuperview];
        [self.overTimeView removeFromSuperview];
    } fail:^(NSError *error) {
        [self.overTimeView removeFromSuperview];
        self.overTimeView = [[GFOverTimeView alloc] initWithFrame:self.view.frame withButtonBlock:^(UIButton *button) {
            [self.view addSubview:self.waitView];
            [self handleDataTheLastSearchResult];
        }];
        [self.waitView removeFromSuperview];
        [self.view addSubview:self.overTimeView];
    }];
}
#pragma mark - 创建tableView
- (void)createTableView {
    self.tableViewForResult = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    self.tableViewForResult.delegate = self;
    self.tableViewForResult.dataSource = self;
    [self.tableViewForResult registerClass:[GFNearResturtantTableViewCell class] forCellReuseIdentifier:@"resturtant"];
    [self.tableViewForResult registerClass:[UITableViewCell class] forCellReuseIdentifier:@"null"];
    self.tableViewForResult.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableViewForResult.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refresh:)];
    self.tableViewForResult.footer.hidden = YES;
    [self.view addSubview:self.tableViewForResult];
}
#pragma mark - 上拉加载
- (void)refresh:(MJRefreshFooter *)footer {
    [self.view addSubview:self.waitView];
    self.page ++;
    [self.tableViewForResult.footer beginRefreshing];
    [self.tableViewForResult.footer endRefreshing];
    [self handleDataTheLastSearchResult];
}
#pragma mark - row number
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.arrayForLastSearchResult.count != 0) {
        return self.arrayForLastSearchResult.count;
    } else {
        return 1;
    }
    
}
#pragma mark - cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (self.arrayForLastSearchResult.count != 0) {
        GFNearResturtantTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"resturtant"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.arrayForLastSearchResult[indexPath.row];
        return cell;
    } else {
        UITableViewCell *cellForNull = [tableView dequeueReusableCellWithIdentifier:@"null"];
        if (cellForNull == nil) {
            cellForNull = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"null"];
        }
        cellForNull.selectionStyle = UITableViewCellSelectionStyleNone;
        cellForNull.textLabel.text = @"暂无结果";
        cellForNull.textLabel.textAlignment = NSTextAlignmentCenter;
        cellForNull.textLabel.font = [UIFont systemFontOfSize:13];
        cellForNull.textLabel.textColor = [UIColor lightGrayColor];
        return cellForNull;
        
    }
    
}
#pragma mark - 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.arrayForLastSearchResult.count != 0) {
        return ScreenHeight / 5;
    } else {
        return self.tableViewForResult.frame.size.height;
    }
}
#pragma mark - 视图将要出现
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.locationService.delegate = self;
}
#pragma mark - 视图将要消失
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.locationService.delegate = nil;
}
#pragma mark - cell点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.arrayForLastSearchResult != 0) {
        GFNearResturtantModel *model = [self.arrayForLastSearchResult objectAtIndex:indexPath.row];
        GFResturtantDetialViewController *rdvc = [[GFResturtantDetialViewController alloc] initWithId:model.place_id withSession:self.sessionId];
        [self.navigationController pushViewController:rdvc animated:1];
    }
}
@end
